package com.dataart.zipbackup;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class TextProcessor {
	ArrayList<String> emailarray = new ArrayList<String>(); // it has to be private or public
	ArrayList<String> phonearray = new ArrayList<String>();

	public void processText(InputStream inputStream, OutputStream outputStream) throws IOException {
			InputStreamReader reader = new InputStreamReader(inputStream);
			BufferedReader bufferedreader = new BufferedReader(reader);
			String content;
			BufferedWriter bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(outputStream));
			while ((content = bufferedreader.readLine()) != null) {
				String tempstringphone = "";
				content = content.replaceAll("[; , \\s \\t]", " ");
				content = content.replace("(101)", "(401)");
				content = content.replace("(202)", "(802)");
				content = content.replace("(301)", "(321)");
				String[] splitline = content.split("\\s+");
				for (int x = 0; x < splitline.length; x++) {
					String newline = splitline[x];
					if (newline.contains("@")) {
						String email = newline;
						email = email.replaceAll("[; , \\s \\t]", "");
						emailarray.add(email);
					}
					if (!newline.contains("@")) {
						String phone = newline;
						phone = phone.replaceAll("[-]", "");
						tempstringphone += phone;
					}
				}
				phonearray.add(tempstringphone);
				bufferedWriter.write(content);
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
		
	}
	public void writePhone(OutputStream out) throws IOException {
		ArrayList<String> phoneArrayMod = phonearray;
		ArrayList<String> uniquePhone = new ArrayList<String>(
				new HashSet<String>(phoneArrayMod));
		Collections.sort(uniquePhone);
		phonearray = uniquePhone;

		PrintWriter writerPhone = new PrintWriter(out);
		for (String str : phonearray) {
			writerPhone.println(str);
		}
		writerPhone.flush();
	}

	public void writeEmail(OutputStream out) throws FileNotFoundException {
		ArrayList<String> uniqueEmail = new ArrayList<String>(
				new HashSet<String>(emailarray));
		Collections.sort(uniqueEmail);
		emailarray = uniqueEmail;
		PrintWriter writerEmail = new PrintWriter(out);
		for (String str : emailarray) {
			writerEmail.println(str);
		}
		writerEmail.flush();
	}
}
